package figure8.GUI;

import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.UUID;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import figure8.Controller;
import figure8.LoopTiming;
import figure8.Project;
import figure8.Network.Client;
import figure8.Network.Message;
import figure8.Network.Message.Type;

public class NetworkConnectWindow extends JFrame {
	public NetworkConnectWindow(final Controller controller) {
		super();
		
		final JFrame window = this;
		
		this.setLayout(new GridLayout(3, 2, 2, 2));
		this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/figure8/GUI/Fig8-small.png"));
		this.setAlwaysOnTop(true);
		
		this.add(new JLabel("IP Address"));
		final JTextField addressField = new JTextField("127.0.0.1");
		this.add(addressField);
		
		this.add(new JLabel("Port"));
		final JTextField portField = new JTextField("8888");
		this.add(portField);
		
		final JButton connect = new JButton("Connect");
		connect.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {				
				int port = Integer.parseInt(portField.getText());
				String address = addressField.getText();
				
				String name = "Network Project " + UUID.randomUUID();
				
				JFileChooser newFC = new JFileChooser();
				newFC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int returnVal = newFC.showDialog(window, "Save network project");
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					String dir = newFC.getSelectedFile().getAbsolutePath();
					File projectDir = new File(dir + File.separator + name);
					File directory = new File(dir);
					//controller.setProject(new Project(timing, name.getText(), projectDir));
					
					controller.setProject(new Project(new LoopTiming(1, 1, 1, 1), name, directory));
				} else {
					System.out.println("Connect window cancel button clicked");
				}
				
				controller.connect(address, port);
				
				window.dispose();
			}
		});

		this.add(connect);

		this.pack();
		this.setVisible(true);
	}
} 
